package com.shelpe.services.auth.provider.token;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map.Entry;

import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

public class AdditionalJwtAccessTokenConverter extends JwtAccessTokenConverter {

	@Override
	public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
		if(accessToken instanceof DefaultOAuth2AccessToken){
			((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(new HashMap<String,Object>());
		}
		
		if(authentication != null && authentication.getOAuth2Request() != null && authentication.getOAuth2Request().getExtensions() != null){
			for(Entry<String, Serializable> en : authentication.getOAuth2Request().getExtensions().entrySet()){
				accessToken.getAdditionalInformation().put(en.getKey(), en.getValue().toString());
			}
		}
		return super.enhance(accessToken, authentication);
	}

}
